import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { ICarsHome, ICarBrand } from '@/utils/interface';
import { getCarsHome, getCarBrand } from '@/services/index';

// 模板数据
export interface CarsModelState {
  carsList: ICarsHome[]; //获取全部汽车品牌接口
  carBrandList: ICarBrand[]; //汽车车系数据
  name: string;
  obj: any;
}
// 模板类型
export interface CarsModelType {
  namespace: 'cars';
  state: CarsModelState;
  effects: {
    getCarsHome: Effect;
    getCarBrand: Effect;
  };
  reducers: {
    save: Reducer<CarsModelState>;
  };
}
const CarsModel: CarsModelType = {
  namespace: 'cars',
  state: {
    carsList: [],
    carBrandList: [],
    name: '',
    obj: {},
  },
  // 异步操作，理解为vuex中的action, async/await理解为generator函数的语法糖
  effects: {
    //获取全部汽车品牌接口
    *getCarsHome({ payload }, { call, put }) {
      let result = yield call(getCarsHome);
      const list = [
        'A',
        'B',
        'C',
        'D',
        'F',
        'G',
        'H',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'W',
        'X',
        'Y',
        'Z',
      ];
      const obj: any = {};
      list.forEach((item, index) => {
        obj[item] = [];
        // 把字符串转换为大写
        (result.data as ICarsHome[]).forEach((i) => {
          if (i.Spelling[0].toLocaleUpperCase() === item) {
            obj[item].push(i);
          }
        });
      });
      yield put({
        type: 'save',
        payload: { carsList: result.data, obj },
      });
    },
    *getCarBrand({ payload }, { call, put }) {
      let result = yield call(getCarBrand, payload);
      // debugger;
      yield put({
        type: 'save',
        payload: { carBrandList: result.data },
      });
    },
    // 添加考试
    // *getExam({payload},{call,put}){
    //     let result = yield call(getExam, payload)
    //     return result
    //  },
  },
  // 同步操作，理解为vuex中的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default CarsModel;
